package com.ruoyi.netty;

import com.ruoyi.netty.initailizer.WebSocketServerInitailizer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetSocketAddress;
import java.util.concurrent.Executor;

//@Component
public class WebSocketNettyServer {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketNettyServer.class);

    @Autowired
    private Executor nettyServerExecutor;
    @Autowired
    private WebSocketServerInitailizer webSocketServerInitailizer;

    @Value("${netty.port}")
    private int port;

    //@PostConstruct
    public void start() throws Exception {
        //异步开启netty服务
        nettyServerExecutor.execute(()-> {
            try {
                this.startNettyServer();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

    }

    private void startNettyServer() throws InterruptedException {
        logger.info("netty启动中...");
        //netty线程组
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup work = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boss,work)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(port))
                    //netty自定义初始配置
                    .childHandler(this.webSocketServerInitailizer);
            //服务器异步创建绑定
            ChannelFuture cf = serverBootstrap.bind().sync();
            logger.info("{} 启动正在监听：{} ",WebSocketNettyServer.class, cf.channel().localAddress());
            //关闭服务器通道
            cf.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 释放线程池资源
            boss.shutdownGracefully().sync();
            work.shutdownGracefully().sync();
            // 优雅退出，释放线程池资源
            logger.info("netty关闭中...");
        }
    }


    private void print() {
        logger.info("\n" +
                "███╗   ██╗███████╗████████╗████████╗██╗   ██╗    ██╗      ██████╗  █████╗ ██████╗     ████████╗██╗  ██╗███████╗    ███████╗██╗   ██╗ ██████╗ ██████╗███████╗███████╗███████╗\n" +
                "████╗  ██║██╔════╝╚══██╔══╝╚══██╔══╝╚██╗ ██╔╝    ██║     ██╔═══██╗██╔══██╗██╔══██╗    ╚══██╔══╝██║  ██║██╔════╝    ██╔════╝██║   ██║██╔════╝██╔════╝██╔════╝██╔════╝██╔════╝\n" +
                "██╔██╗ ██║█████╗     ██║      ██║    ╚████╔╝     ██║     ██║   ██║███████║██║  ██║       ██║   ███████║█████╗      ███████╗██║   ██║██║     ██║     █████╗  ███████╗███████╗\n" +
                "██║╚██╗██║██╔══╝     ██║      ██║     ╚██╔╝      ██║     ██║   ██║██╔══██║██║  ██║       ██║   ██╔══██║██╔══╝      ╚════██║██║   ██║██║     ██║     ██╔══╝  ╚════██║╚════██║\n" +
                "██║ ╚████║███████╗   ██║      ██║      ██║       ███████╗╚██████╔╝██║  ██║██████╔╝       ██║   ██║  ██║███████╗    ███████║╚██████╔╝╚██████╗╚██████╗███████╗███████║███████║\n" +
                "╚═╝  ╚═══╝╚══════╝   ╚═╝      ╚═╝      ╚═╝       ╚══════╝ ╚═════╝ ╚═╝  ╚═╝╚═════╝        ╚═╝   ╚═╝  ╚═╝╚══════╝    ╚══════╝ ╚═════╝  ╚═════╝ ╚═════╝╚══════╝╚══════╝╚══════╝\n" +
                "                                                                                                                                                                            \n");
    }

}
